package com.inet.consoleservices;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.inet.util.L;
import com.inet.util.Utils;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;

public class UpdateService extends Service{

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		downLoadApk();
	}
	
	/* 
	 * 开启线程准备下载 
	 */ 
	private void downLoadApk() {  	     
	    new Thread(){  
	        @Override  
	        public void run() {  
	            try {  
	                File file = downLoadApk(Utils.getPropertiesValue("download_update_apk")); 
	                sleep(3000);  
	                installApk(file);  
	            } catch (Exception e) {  
	              L.i("downloadApk fail"); 
	            }  
	        }}.start();  
	}  
	
	/* 
	 * 从服务器中下载APK 
	 */
	private static File downLoadApk(String path){  
		 //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
	    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
	        URL url;
	        File file = null;
			try {
				url = new URL(path);
	        HttpURLConnection conn =  (HttpURLConnection) url.openConnection();  
	        conn.setConnectTimeout(5000);  
	        InputStream is = conn.getInputStream();  
	        file = new File(Environment.getExternalStorageDirectory(), "ConsoleServices.apk");  
	        FileOutputStream fos = new FileOutputStream(file);  
	        BufferedInputStream bis = new BufferedInputStream(is);  
	        byte[] buffer = new byte[1024];  
	        int len ;  
	        while((len =bis.read(buffer))!=-1){  
	            fos.write(buffer, 0, len);  
	        }  
	        fos.close();  
	        bis.close();  
	        is.close();  
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				L.i("downLoadApk IOException=="+e.toString());;
			} 
	        return file;  
	    }  
	    else{  
	        return null;  
	    }  
	}  
	
	//安装apk 
	private void installApk(File file) {  
	    Intent intent = new Intent();  
	  //执行动作  
	    intent.setAction(Intent.ACTION_VIEW);  
	    //执行的数据类型  
	    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
	    startActivity(intent);  
	}  
}
